package com.example.blog.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.example.blog.entity.Blog;
import com.example.blog.entity.BlogLike;
import com.example.blog.mapper.BlogLikeMapper;
import com.example.blog.mapper.BlogMapper;
import com.example.blog.service.BlogService;

@Service
public class BlogServiceImpl implements BlogService {

    @Autowired
    private BlogMapper blogMapper;
    
    @Autowired
    private BlogLikeMapper blogLikeMapper;
    
    @Override
    @Transactional
    public Map<String, Object> createBlog(Blog blog) {
        Map<String, Object> map = new HashMap<>();
        
        try {
            // 设置创建时间
            blog.setCreateTime(new Date());
            
            // 初始化计数器
            blog.setViews(0);
            blog.setLikes(0);
            blog.setComments(0);
            
            // 默认为草稿状态
            if (blog.getIsPublished() == null) {
                blog.setIsPublished(false);
            }
            
            // 默认为启用状态
            blog.setIsDisabled(false);
            
            int result = blogMapper.insert(blog);
            if (result > 0) {
                map.put("success", true);
                map.put("message", "创建成功");
                map.put("blogId", blog.getBlogId());
            } else {
                map.put("success", false);
                map.put("message", "创建失败");
            }
        } catch (Exception e) {
            map.put("success", false);
            map.put("message", "系统异常：" + e.getMessage());
        }
        
        return map;
    }

    @Override
    @Transactional
    public Map<String, Object> updateBlog(Blog blog) {
        Map<String, Object> map = new HashMap<>();
        
        try {
            // 查询原博客信息
            Blog originalBlog = blogMapper.selectByPrimaryKey(blog.getBlogId());
            if (originalBlog == null) {
                map.put("success", false);
                map.put("message", "博客不存在");
                return map;
            }
            
            // 设置更新时间
            blog.setUpdateTime(new Date());
            
            // 保留原有计数器
            blog.setViews(originalBlog.getViews());
            blog.setLikes(originalBlog.getLikes());
            blog.setComments(originalBlog.getComments());
            
            // 保留原有状态
            blog.setIsDisabled(originalBlog.getIsDisabled());
            
            int result = blogMapper.updateByPrimaryKey(blog);
            if (result > 0) {
                map.put("success", true);
                map.put("message", "更新成功");
            } else {
                map.put("success", false);
                map.put("message", "更新失败");
            }
        } catch (Exception e) {
            map.put("success", false);
            map.put("message", "系统异常：" + e.getMessage());
        }
        
        return map;
    }

    @Override
    @Transactional
    public boolean updatePublishStatus(Integer blogId, Boolean isPublished) {
        try {
            int result = blogMapper.updatePublishStatus(blogId, isPublished);
            return result > 0;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    @Transactional
    public boolean updateDisableStatus(Integer blogId, Boolean isDisabled) {
        try {
            int result = blogMapper.updateDisableStatus(blogId, isDisabled);
            return result > 0;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    @Transactional
    public boolean deleteBlog(Integer blogId) {
        try {
            int result = blogMapper.deleteByPrimaryKey(blogId);
            return result > 0;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public Blog getBlogById(Integer blogId) {
        return blogMapper.selectByPrimaryKey(blogId);
    }

    @Override
    public List<Blog> getAllBlogs() {
        return blogMapper.selectAll();
    }

    @Override
    public List<Blog> getAllPublishedBlogs() {
        return blogMapper.selectAllPublished();
    }

    @Override
    public List<Blog> getBlogsByUserId(Integer userId) {
        return blogMapper.selectByUserId(userId);
    }

    @Override
    public List<Blog> getPublishedBlogsByUserId(Integer userId) {
        return blogMapper.selectPublishedByUserId(userId);
    }

    @Override
    public List<Blog> getBlogsByTypeId(Integer typeId) {
        return blogMapper.selectByTypeId(typeId);
    }

    @Override
    public List<Blog> getHotBlogs(Integer limit) {
        return blogMapper.selectHotBlogs(limit);
    }

    @Override
    public List<Blog> searchBlogs(String keyword) {
        return blogMapper.selectByKeyword(keyword);
    }

    @Override
    @Transactional
    public boolean incrementViews(Integer blogId) {
        try {
            int result = blogMapper.incrementViews(blogId);
            return result > 0;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    @Transactional
    public Map<String, Object> likeBlog(Integer userId, Integer blogId) {
        Map<String, Object> map = new HashMap<>();
        
        try {
            // 查询是否已点赞
            BlogLike blogLike = blogLikeMapper.selectByPrimaryKey(userId, blogId);
            
            if (blogLike != null) {
                // 已有记录，更新点赞状态
                if (blogLike.getIsLiked()) {
                    map.put("success", false);
                    map.put("message", "已经点赞过了");
                    return map;
                } else {
                    // 之前取消过点赞，现在重新点赞
                    blogLikeMapper.updateLikeStatus(userId, blogId, true);
                    blogMapper.updateLikes(blogId, 1);
                    map.put("success", true);
                    map.put("message", "点赞成功");
                }
            } else {
                // 第一次点赞
                BlogLike newLike = new BlogLike();
                newLike.setUserId(userId);
                newLike.setBlogId(blogId);
                newLike.setIsLiked(true);
                blogLikeMapper.insert(newLike);
                blogMapper.updateLikes(blogId, 1);
                map.put("success", true);
                map.put("message", "点赞成功");
            }
        } catch (Exception e) {
            map.put("success", false);
            map.put("message", "系统异常：" + e.getMessage());
        }
        
        return map;
    }

    @Override
    @Transactional
    public Map<String, Object> unlikeBlog(Integer userId, Integer blogId) {
        Map<String, Object> map = new HashMap<>();
        
        try {
            // 查询是否已点赞
            BlogLike blogLike = blogLikeMapper.selectByPrimaryKey(userId, blogId);
            
            if (blogLike != null && blogLike.getIsLiked()) {
                // 取消点赞
                blogLikeMapper.updateLikeStatus(userId, blogId, false);
                blogMapper.updateLikes(blogId, -1);
                map.put("success", true);
                map.put("message", "取消点赞成功");
            } else {
                map.put("success", false);
                map.put("message", "还没有点赞过");
            }
        } catch (Exception e) {
            map.put("success", false);
            map.put("message", "系统异常：" + e.getMessage());
        }
        
        return map;
    }

    @Override
    public boolean isLikedByUser(Integer userId, Integer blogId) {
        BlogLike blogLike = blogLikeMapper.selectByPrimaryKey(userId, blogId);
        return blogLike != null && blogLike.getIsLiked();
    }

    @Override
    public List<Integer> getLikedBlogIdsByUserId(Integer userId) {
        return blogLikeMapper.selectLikedBlogIdsByUserId(userId);
    }

    @Override
    public Map<String, Object> getAllBlogs(Integer pageNum, Integer pageSize, String query, Integer typeId) {
        Map<String, Object> result = new HashMap<>();
        
        // 计算偏移量
        int offset = (pageNum - 1) * pageSize;
        
        // 获取分页数据
        List<Blog> blogs = blogMapper.selectAllBlogs(query, typeId, offset, pageSize);
        
        // 获取总数
        int total = blogMapper.countAllBlogs(query, typeId);
        
        // 计算总页数
        int totalPages = (int) Math.ceil((double) total / pageSize);
        
        result.put("content", blogs);
        result.put("total", total);
        result.put("totalPages", totalPages);
        result.put("currentPage", pageNum);
        
        return result;
    }
    
    @Override
    public Map<String, Object> getAllPublishedBlogs(Integer pageNum, Integer pageSize, String query, Integer typeId) {
        Map<String, Object> result = new HashMap<>();
        
        // 计算偏移量
        int offset = (pageNum - 1) * pageSize;
        
        // 获取分页数据
        List<Blog> blogs = blogMapper.selectPublishedBlogs(query, typeId, offset, pageSize);
        
        // 获取总数
        int total = blogMapper.countPublishedBlogs(query, typeId);
        
        // 计算总页数
        int totalPages = (int) Math.ceil((double) total / pageSize);
        
        result.put("content", blogs);
        result.put("total", total);
        result.put("totalPages", totalPages);
        result.put("currentPage", pageNum);
        
        return result;
    }

    @Override
    public List<Blog> getTopBlogs(String sortType) {
        if (sortType == null) {
            sortType = "latest";
        }
        return blogMapper.selectTopBlogs(sortType);
    }

    @Override
    @Transactional
    public boolean incrementLikes(Integer blogId) {
        try {
            int result = blogMapper.incrementLikes(blogId);
            return result > 0;
        } catch (Exception e) {
            return false;
        }
    }
} 